using System;
using System.Collections.Generic;
using System.Text;
using CodePlex.Resourceful.Wadl;
using CodePlex.Resourceful.Bookmarks.Model;

namespace CodePlex.Resourceful.Bookmarks.Controllers
{
    abstract public class BaseController
    {
        private readonly BookmarkEngine _engine;
        protected BaseController(BookmarkEngine engine)
        {
            _engine = engine;
        }

        protected BookmarkEngine Engine
        {
            get
            {
                return _engine;
            }
        }

        // helper methods
        public void RenderStatus(IRepresentationContext context, HttpStatus status)
        {
            if (context.Request.Accepts(MediaType.TextHtml))
            {
                context.Response.Render(status,
                    MediaType.TextHtml,
                    string.Format("<h2>{0}</h2>", status));

            }
            else
            {
                context.Response.Render(status);
            }

        }



        protected bool IsAuthorized(IRepresentationContext context, UserAccount user)
        {
            if (user.Name != context.BasicAuthUsername || user.Password != context.BasicAuthPassword)
            {
                context.Response.SetHeader(HttpHeader.WWWAuthenticate, @"Basic realm=""Social bookmarking service""");
                this.RenderStatus(context, HttpStatus.Unauthorized);
                return false;
            }
            return true;
        }

        protected string UserUrl(IRepresentationContext context, string username)
        {
            return string.Format("{0}users/{1}", context.RootUri, username);
        }


        protected string BookmarkUrl(IRepresentationContext context, string username, Bookmark bookmark)
        {
            return string.Format("{0}users/{1}/bookmarks/{2}", context.RootUri, username, bookmark.URIHash);
        }

        protected string BookmarksUrl(IRepresentationContext context, string username)
        {
            return string.Format("{0}users/{1}/bookmarks", context.RootUri, username);
        }
    }
}
